package com.basic.exception;

import com.alibaba.fastjson.JSONObject;
import com.basic.error.AppError;
import org.apache.commons.lang3.StringUtils;
import org.omg.CORBA.Object;

import java.text.MessageFormat;

/**
 * @author Duan SanMao
 * @date 2021/8/14
 */

public class AppException extends RuntimeException {

    private static final long serialVersionUID = 190993434343434L;

    private String errorCode;

    private String errorMsg;

    private Object[] params;
    private JSONObject result;


    public AppException(AppError appError) {
        super(appError.getErrorCode());
        this.errorCode = appError.getErrorCode();
        this.errorMsg = appError.getErrorMessage();
    }

    public AppException(AppError appError, JSONObject result) {
        super(appError.getErrorCode());
        this.errorCode = appError.getErrorCode();
        this.errorMsg = appError.getErrorMessage();
        this.result = result;
    }

    public AppException(String errorCode, String errorMsg) {
        super(errorCode);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public AppException(String errorCode, String errorMsg, Object... params) {
        super(errorCode);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
        this.params = params;
    }

    public AppException(AppError appError, Object... params) {
        super(appError.getErrorCode());
        this.errorCode = appError.getErrorCode();
        this.errorMsg = appError.getErrorMessage();
        this.params = params;
    }

    public AppException(String errorCode, Throwable cause) {
        super(errorCode, cause);
        this.errorCode = errorCode;
    }

    public AppException(Throwable cause) {
        super(cause);
    }

    public String getErrorCode() {
        return errorCode;
    }

    public String getErrorMsg() {
        String message = null;

        if(StringUtils.isNoneBlank(this.errorMsg)){
            if(this.params!=null && this.params.length >0){
                message = MessageFormat.format(this.errorMsg, (java.lang.Object) this.params);
            }else{
                message = this.errorMsg;
            }
        }else{
            message=super.getMessage();
        }
        return errorMsg;
    }

    public JSONObject getResult() {
        return result;
    }

}
